//promise封装
const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1/"

let ajaxnum = 0; //loading计数器

//使用promise
const request = function (param) {
  //加载loading效果
  ajaxnum++
  wx.showLoading({
    title: '正在加载',
    mask: true
  })
  param.url = baseUrl + param.url;
  return new Promise((resolve, reject) => {
    wx.request({
      ...param,
      timeout: 5000,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
      //成功失败时都会调用的
      complete: () => {
        ajaxnum--;
        //没有等待发送请求的时候  关闭loading效果
        if (ajaxnum === 0) {
          wx.hideLoading()
        }

      }

    })

  })
}

//分类页面
const categoryApi = {
  categorydata: function (data) {
    return request({
      url: 'categories'
      // method: "POST",
      // data: data
    })
  }
}
//商品列表
const goodlistApi = {
  goodlistdata: function (data) {
    return request({
      url: 'goods/search',
      // method: "POST",
      data: data
    })
  }
}
//商品详情
const gooddetailApi = {
  gooddetaildata: function (data) {
    return request({
      url: 'goods/detail',
      // method: "POST",
      data: data
    })
  },
  //搜索
  goodqsearch: function (data) {
    return request({
      url: 'goods/qsearch',
      // method: "POST",
      data: data
    })
  }
}

//主页
const indexApi = {
  swipwedata: function () {
    return request({
      url: 'home/swiperdata'
    })
  },
  bannerdata: function () {
    return request({
      url: 'home/catitems'
    })
  },
  contentdata: function () {
    return request({
      url: 'home/floordata'
    })
  }
}
//定单接口
const myApi = {
  //创建订单接口

  createOrder: function (data) {
    return request({
      url: "my/orders/create",
      method: "POST",
      data: data
    })
  },
  //获取支付参数
  reqUnifiedorder: function (data) {
    return request({
      url: "my/orders/req_unifiedorder",
      method: "POST",
      data: data
    })
  },
  //查看订单支付状态
  checkOrder: function (data) {
    return request({
      url: "my/orders/chkOrder",
      method: "POST",
      data: data,
      header: {
        a: 123
      }
    })
  },
}

const API = {
  categoryApi,
  indexApi,
  goodlistApi,
  gooddetailApi,
  myApi
}


export default API



//promise封装
// const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1/"
// const request = function(aff){
//   aff.url = baseUrl + aff.url;
//   return new Promise((resolve,reject)=>{
//     wx:wx.request({
//       ...aff,
//       timeout: 5000,
//       success: (res) => {
//         resolve(res)
//       },
//       fail: (err) => {
//         reject(err)
//       },
//     })
//   })
// }
// export default request